﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;
using bmapi.SQLServerAccess;
using static bmapi.Models.ShowModel;

namespace bmapi.Controllers
{
    [Route("FtpAmend")]
    public class FtpAmendController : BuyiController
    {
        [HttpGet]
        public HttpResponseMessage Get()
        {
            try
            {
                SQLCommand sc = new SQLCommand("SELECT key_val FROM System_tb where key_name='FtpPassword' or key_name='WriteDebug'");
                DataTable dt = sc.ExecuteScalars();
                if (dt == null)
                    return AssistFun.toJson(new { status = 201, tip = "没有任何FTP相关数据" });
                string ftpkeyval = dt.Rows[0][0].ToString();
                string bugkeyval = dt.Rows[1][0].ToString();
                if (ftpkeyval == null)
                    return AssistFun.toJson(new { status = 201, tip = "没有ftp账户" });
                if (bugkeyval == null)
                    return AssistFun.toJson(new { status = 201, tip = "没有日志设置" });
                else
                    return AssistFun.toJson(new { status = 200, tip = "成功", data = new { total = 1, rows = 1, ftp = new { username = "BuyiMesUser", newpassword = ftpkeyval, bug = bugkeyval } } });
            }
            catch (Exception e)
            {
                WriteLog("FtpAmend-get",e.Message);
                throw;
            }           
        }
        [HttpPut,Route("FtpAmend/updateftppwd")]
        public HttpResponseMessage PutPassWord(dynamic obj)
        { 
            string pwd = obj.newpassword.ToString();
            SQLCommand sc = new SQLCommand("UPDATE System_tb SET key_val=@newpassword where key_name='FtpPassword'", "@newpassword", pwd);
            int count = sc.ExecuteNonQuery();
            return FtpRespond(count);
        }

        [HttpPut,Route("FtpAmend/updatebugflg")]
        public HttpResponseMessage PutDebug(dynamic obj)
        {
            string bug = obj.bug.ToString();
            SQLCommand sc = new SQLCommand("UPDATE System_tb SET key_val=@bug where key_name='WriteDebug'", "@bug", bug);
            int count = sc.ExecuteNonQuery();
            return  FtpRespond(count);
        }

        private HttpResponseMessage FtpRespond(int count)
        {
            if (count > 0)
                return AssistFun.toJson(new RespondModel(200, "修改成功"));
            else
                return AssistFun.toJson(new RespondModel(201, "修改失败"));
        }
    }
}
